package com.xsz.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xsz.entity.Product;
import com.xsz.service.ProductService;
import com.xsz.util.ResultVOUtil;
import com.xsz.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("product")
@Api(value = "产品控制类")
public class ProductController {
    @Resource
    ProductService productService;

    /**
     *  GET /get
     * POST /create
     * PUT /update
     * DELETE /delete
     * @param product
     * @return
     */
    @ApiOperation(value = "添加API")
    @PostMapping("/add")
    public ResultVO add(@RequestBody Product product) {
        return ResultVOUtil.success(productService.add(product));
    }

    @ApiOperation(value = "修改API")
    @PutMapping("/update")
    public ResultVO update(@RequestBody Product product) {
        if(productService.update(product) == 1){
            return ResultVOUtil.success();
        }else{
            return ResultVOUtil.error(500,"修改失败");
        }
    }

    @ApiOperation(value = "删除API")
    @DeleteMapping("/delete/{id}")
    public ResultVO delete(@PathVariable("id") String id) {
        if(productService.delete(id) == 1){
            return ResultVOUtil.success();
        }else{
            return ResultVOUtil.error(500,"删除失败");
        }
    }

    @ApiOperation(value = "根据id查询API")
    @GetMapping("/selectById/{id}")
    public ResultVO selectById(@PathVariable("id") String id) {
            return ResultVOUtil.success(productService.selectById(id));
    }

    @ApiOperation(value = "查询所有API")
    @GetMapping("/getAll")
    public ResultVO getAll() {
        return ResultVOUtil.success(productService.getAll());
    }

    @ApiOperation(value = "分页查询所有API")
    @GetMapping("/getpageAll/{startPage}/{limit}")
    public ResultVO getpageAll(@PathVariable("startPage") String startPage,@PathVariable("limit") String limit) {
        //startPage起始页，limit每页记录数这两个参数
        //注意:这里的startPage是从1开始算起的，0和1都是指第一页
        //创建Page对象，startPage，limit参数传入，必须位于从数据库查询数据的语句之前，否则不生效
        Page page= PageHelper.startPage(Integer.parseInt(startPage), Integer.parseInt(limit));
        //ASC是根据id 正向排序，DESC是反向排序
        PageHelper.orderBy("id ASC");
        //从数据库查询，这里返回的的allUser就已经分页成功了
        List<Product> allUser = productService.getAll();
        //获取查询记录总数，必须位于从数据库查询数据的语句之后，否则不生效
        long total = page.getTotal();
        //分页的信息
        HashMap<String, Object> map = new HashMap<>();
        map.put("data",allUser);
        map.put("count",total);
        return ResultVOUtil.success(map);
    }
}
